import React from 'react';
import PropTypes from 'prop-types';
import cn from 'classnames';

import { datetime } from '../../../../common/formatter';

import s from './ChangeHistory.module.css';

export default function ChangeHistory({
	className,
	sitePortraitHistory,
	selectedPatchId,
	onChange,
}) {
	const history = React.useMemo(() => {
		return sitePortraitHistory.map(h =>
			JSON.parse(h?.result?.addition?.patches || '[]').reduce(
				(obj, x) => {
					/**
					 * 历史保存的 op 和实际的操做是相反的
					 */
					if (x.op === 'add') {
						obj.remove += 1;
					} else if (x.op === 'remove') {
						obj.add += 1;
					}
					return obj;
				},
				{ add: 0, remove: 0, ...h }
			)
		);
	}, [sitePortraitHistory]);

	return (
		<div className={cn(className, s.changeHistory)}>
			<div className={s.title}>变化历史</div>
			<div
				className={cn(s.item, {
					[s.active]: !selectedPatchId,
				})}
				onClick={() => onChange(null)}
			>
				<div className={s.changes}>最新版本</div>
			</div>
			{history?.map(x => (
				<div
					key={x._id}
					className={cn(s.item, {
						[s.active]: selectedPatchId === x._id,
					})}
					onClick={() => onChange(x._id)}
				>
					<div className={s.changes}>
						<span className={cn(s.count, s.add)}>
							<span>添加：</span>
							<span>{x.add}</span>
						</span>
						<span className={cn(s.count, s.remove)}>
							<span>移除：</span>
							<span>{x.remove}</span>
						</span>
					</div>
					<div className={s.createTime}>{datetime(x.endTime)}</div>
				</div>
			))}
		</div>
	);
}

ChangeHistory.propTypes = {
	className: PropTypes.string,
	sitePortraitHistory: PropTypes.arrayOf(
		PropTypes.shape({
			_id: PropTypes.string.isRequired,
		})
	),
	selectedPatchId: PropTypes.string,
	onChange: PropTypes.func.isRequired,
};

ChangeHistory.defaultProps = {
	className: s.changeHistory,
};
